<template>
    <div class="e-form">
        <!-- <BillTop title="外协台账检查记录新增" @cancel="handleClose"></BillTop> -->
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData" label-width="200px" :rules="rules">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="检查日期：" prop="checkDate">
                                            <el-date-picker
                                                v-model="formData.checkDate"
                                                type="date"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                :clearable="false"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="检查类型：" prop="checkType">
                                            <el-select v-model="formData.checkType">
                                                <el-option :value="item.value"  :label="item.label" v-for="item,index in checkType" :key="index" ></el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="检查人：" prop="checker">
                                            <el-input v-model="formData.checker">
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="录入人：" prop="recorder">
                                            <el-input v-model="formData.recorder" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item  label="检查内容：" prop="checkRemarks">
                                            <el-input type="textarea" v-model="formData.checkRemarks" placeholder="请输入内容"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" bucketName="facilityaccount" />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <span class="tip"><span style="color: red; margin-right: 0">*</span>为必填项</span>
            <el-button
                type="primary"
                class="btn-blue"
                @click="saveData"
                size="small"
                v-debounce
                >保存</el-button
            >
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/equipAccount.js'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻
            formData: {
                'billId': this.$route.query.billid,
                'changeType': 1,
                'checkDate': '',
                'checkRemarks': '',
                'checkType': null,
                'checker': '',
                'id': '',
                'recorder': ''
            },
            rules: {
                checkDate: [
                    { required: true, message: '请选择检查日期', trigger: 'change' },
                ],
                checkType: [
                    { required: true, message: '请选择检查类型', trigger: 'change'  },
                ],
                checker: [
                    { required: true, message: '请填写检查人', trigger: 'blur'  },
                ],
                recorder: [
                    { required: true, message: '请填写录入人', trigger: 'blur'  },
                ],
                checkRemarks: [
                    { required: true, message: '请填写检查内容', trigger: 'blur'  },
                ]
            },
            billid: this.$route.query.billid,
            isNewAdd: true, //判断是新增还是编辑
            id: JSON.parse(localStorage.vuex).auditParams.id,
            attachId: '', //附件id
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            checkType: state => state.equip.equipData.checkType, //检查类型
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return obj.label
            }
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
        AttachComp,
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    created () {
        this.getDicValue()
        if(this.$route.query.isNewAdd === 'true' || this.$route.query.isNewAdd === 'false') {
            this.isNewAdd = JSON.parse(this.$route.query.isNewAdd)
        }
        this.getOnlyId()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'attach']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth
        this.screenHeight = document.documentElement.clientHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    methods: {
        ...mapMutations(['setAuditParams']),
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setList')
        },
        //是否获取生成唯一id
        getOnlyId () {
            //如果是新增前端生成唯一id
            if(this.isNewAdd) {
                this.$Ajax
                    .httpGet({
                        url: '/uid/builder?num=1',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        }
                    }).then(res=>{
                        this.formData.id = res[0]
                        this.attachId = res[0]
                        this.formData.changeType = 1  //新增
                    })
            }else{
                this.attachId = this.id
                request.outAccountCheckRecordBase(this.id).then(res=>{
                    this.formData = res
                    this.formData.changeType = 2 //修改
                })
            }
        },
        //保存数据
        saveData () {
            return new Promise((resolve, reject)=>{
                this.$refs.form.validate(valid => {
                    if(valid) {
                        request.outAccountCheckRecordUpdate([this.formData]).then(res=>{
                            this.formData = res[0]
                            this.clientPop('suc', '保存成功')
                        }).catch(err=>{
                            reject(err)
                            this.setError('baseInfo')
                            this.scorllError()
                        })
                    }else{
                        reject()
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            console.log('clickTabFlag: ', this.clickTabFlag)
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}
</style>
